<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\UserRequest;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 留言板后台用户列表
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = User::orderBy('id', 'desc')->paginate(1);
        return view('admin.user.index', compact('data'));
    }

    /**
     * 留言板后台新增用户
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.user.create');
    }

    /**
     * 留言板后台插入用户
     * Store a newly created resource in storage.
     *
     * @param UserRequest $request
     * @return \Illuminate\Http\Response
     */
    public function store(UserRequest $request)
    {
        $inputs = $request->except('_token');
        $inputs['password'] = bcrypt($inputs['password']);
        $result = User::create($inputs);
        if ($result) {
            return redirect('admin/user');
        } else {
            return redirect()->back()->withErrors(['error' => '添加失败']);
        }
    }

    /**
     * 留言板后台查看用户
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * 留言板后台编辑用户
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $field = User::find($id);
        return view('admin.user.edit', compact('field'));
    }

    /**
     * 留言板后台修改用户
     * Update the specified resource in storage.
     *
     * @param UserRequest $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UserRequest $request, $id)
    {
        $inputs = $request->except('_token', '_method');
        if ($inputs['password'] == '') {
            unset($inputs['password']);
        } else {
            $inputs['password'] = bcrypt($inputs['password']);
        }
        $result = User::where('id', $id)->update($inputs);
        if ($result) {
            return redirect('admin/user');
        } else {
            return redirect()->back()->withErrors(['error' => '编辑失败']);
        }
    }

    /**
     * 留言板后台删除用户
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $result = User::where('id', $id)->delete();
        if ($result) {
            $data = [
                'status' => 0,
                'message' => '用户删除成功!',
            ];
        } else {
            $data = [
                'status' => 1,
                'message' => '用户删除失败，请稍后重试!',
            ];
        }
        return $data;
    }
}
